/*
 * @(#)FormSubmissionManager.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.form.core;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDocument;
import com.dcivision.dms.bean.DmsVersion;
import com.dcivision.dms.core.DocumentOperationManager;
import com.dcivision.dms.dao.DmsDocumentDAObject;
import com.dcivision.dms.dao.DmsVersionDAObject;
import com.dcivision.form.FormConstant;
import com.dcivision.form.bean.FormAttach;
import com.dcivision.form.bean.FormElement;
import com.dcivision.form.bean.FormElementType;
import com.dcivision.form.bean.FormFileAttachment;
import com.dcivision.form.bean.FormPage;
import com.dcivision.form.bean.FormRecord;
import com.dcivision.form.bean.FormSection;
import com.dcivision.form.bean.FormSelectionField;
import com.dcivision.form.bean.FormSelectionFieldOption;
import com.dcivision.form.bean.FormSubmission;
import com.dcivision.form.dao.FormFileAttachmentDAObject;
import com.dcivision.form.dao.FormPageDAObject;
import com.dcivision.form.dao.FormRecordDAObject;
import com.dcivision.form.dao.FormSectionDAObject;
import com.dcivision.form.dao.FormSubmissionDAObject;
import com.dcivision.form.web.MaintFormSubmissionForm;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.Crypt;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.MessageResourcesFactory;
import com.dcivision.framework.PermissionManager;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.AbstractBaseObject;
import com.dcivision.framework.bean.SysFunction;
import com.dcivision.framework.taglib.TagUtil;
import com.dcivision.framework.taglib.html.StandardButtonTag;
import com.dcivision.framework.web.AbstractActionForm;
import com.dcivision.framework.web.WebUtil;
import com.dcivision.workflow.WorkflowErrorConstant;
import com.dcivision.workflow.bean.WorkflowProgressAttachment;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.core.WorkflowContentStoreHandler;
import com.dcivision.workflow.core.WorkflowOperationManager;
import com.dcivision.workflow.core.WorkflowProgressManager;
import com.dcivision.workflow.dao.MtmWfStepFormRecordDAObject;
import com.dcivision.workflow.dao.WorkflowStepDAObject;

/**
  FormSubmissionManager.java

  This class is responsible for workflow operation.

    @author          Scott Tong
    @company         DCIVision Limited
    @creation date   10/1/2003
    @version         $Revision: 1.69.2.9 $
*/

public class FormSubmissionManager {

  public static final String REVISION = "$Revision: 1.69.2.9 $";
 
  private static final Log log = LogFactory.getLog(FormSubmissionManager.class);

  private SessionContainer sessionCon = null;
  private Connection dbConn = null;

  /**
   * Constructor
   *
   * @param sessionContainer
   * @param conn
   */
  public FormSubmissionManager(SessionContainer sessionContainer, Connection conn) {
    this.sessionCon = sessionContainer;
    this.dbConn = conn;
  }

  /**
   * Form Export File content
   * @param formSubmissionID		Form Submission ID
   * @param haveSubSection		true if the form got sub section
   * @return String of the file content

   */

  public String exportFileContent(Integer formSubmissionID, boolean haveSubSection) throws ApplicationException{
    String loginName = this.sessionCon.getUserRecord().getLoginName();
    String loginPsw = Crypt.decrypt(
            this.sessionCon.getUserRecord().getLoginPwd(),
                SystemParameterFactory.getSystemParameter(SystemParameterConstant.CRYPTO_SALT));
    String httpURL = SystemParameterFactory.getSystemParameter(SystemParameterConstant.APPLICATION_BASE_URL) ;
    String content ="";
    String formRecordID ="";
    String tmpContent = "";
    FormHttpOperation formHttpOperation = new FormHttpOperation();
    FormSubmissionDAObject formSubmissionDAO = new FormSubmissionDAObject(this.sessionCon,this.dbConn);
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    try {
      FormSubmission formSubmission = (FormSubmission)formSubmissionDAO.getObjectByID(formSubmissionID);
      formRecordID = formSubmission.getFormRecordID().toString();
      List pageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));
      boolean bl = formHttpOperation.login(httpURL+"/Login.do",loginName,loginPsw);
      String exportFunction = haveSubSection ? "WORKFLOW" : "DMS";
      String url = httpURL+"/form/MaintFormSubmission.do?navMode=V&formRecordID="+formRecordID+"&formSubmissionID="+formSubmissionID+"&exportFunction="+exportFunction+"&SHOW_HEADER_FOOTER=N";
      formHttpOperation.reset() ;
      formHttpOperation.setSubmissionURL(url);
      tmpContent = formHttpOperation.transmit("");
      content += tmpContent.substring(tmpContent.indexOf("<",0),tmpContent.length());

    } catch (Exception e){
      throw new ApplicationException(e);
    }
    return content;
  }

  /**
   * Save Form File to DMS according the specified form submission
   *
   * @param formSubmissionID
   *            Form Submission ID
   * @param rootID
   *            DMS destination Root ID
   * @param parentID
   *            DMS destination Parent ID
   * @param haveSubSection
   *            true if the form got sub section
   * @throws ApplicationException
   */
  public void saveFileToDMS(Integer formSubmissionID,
      String rootID,
      String parentID,
      boolean haveSubSection)throws ApplicationException{

    try{
      String formRecordID ="";
      FormHttpOperation formHttpOperation = new FormHttpOperation();
      FormSubmissionDAObject formSubmissionDAO = new FormSubmissionDAObject(this.sessionCon,this.dbConn);
      FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
      WorkflowProgressManager workflowProgressManager = new WorkflowProgressManager(this.sessionCon,this.dbConn);

      FormSubmission formSubmission = (FormSubmission)formSubmissionDAO.getObjectByID(formSubmissionID);
      formRecordID = formSubmission.getFormRecordID().toString();
      List pageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));
      //  save file to DMS
      if (!Utility.isEmpty(rootID)
          && !Utility.isEmpty(parentID)){
        FormRecordDAObject formRecordDAO = new FormRecordDAObject(this.sessionCon,this.dbConn);
        DocumentOperationManager docOperationManager = new DocumentOperationManager(this.sessionCon,this.dbConn);

        FormRecord formRecord = (FormRecord) formRecordDAO.getObjectByID(new Integer(formRecordID));
        String formCodeTitle = formRecord.getFormCode() + " - " + formRecord.getTitle();
        formCodeTitle = formCodeTitle.length()>FormConstant.FORM_TITLE_LENGTH?formCodeTitle.substring(0, FormConstant.FORM_TITLE_LENGTH)+"...":formCodeTitle ;
        String documentName= formCodeTitle+" (" + formRecord.getFormVersion() + ") - FM" + formSubmissionID +".html";
        //create document
        DmsDocument dmsDocument = new DmsDocument();
        dmsDocument.setDocumentName(documentName);
        dmsDocument.setRecordStatus(GlobalConstant.STATUS_ACTIVE);
        dmsDocument.setItemStatus(DmsVersion.AVAILABLE_STATUS);
        dmsDocument.setParentID(new Integer(parentID));
        dmsDocument.setRootID(new Integer(rootID));
        dmsDocument.setDocumentType(DmsDocument.DOCUMENT_TYPE);
        dmsDocument.setCreateType(DmsOperationConstant.DMS_CREATE_BY_SYSTEM);
      dmsDocument.setPriority(GlobalConstant.PRIORITY_MEDIUM);
        String sContent = exportFileContent(formSubmissionID,haveSubSection);
        InputStream inputStream;
        inputStream = new ByteArrayInputStream(sContent.getBytes("UTF-8"));
        dmsDocument.setItemSize(new Integer(sContent.length()));
        docOperationManager.createDocument(dmsDocument,inputStream,true,null);

      }

    } catch (Exception e){
      throw new ApplicationException(e);
    }
  }

  /**
   * getStorageLocation - Get the storage location for form files
   *
   * @return               the phyiscal location where files uploaded for form are located.
   * @throws ApplicationException
   */
  public String getStorageLocation() throws ApplicationException {
    String attachmentRootFolder = SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
    File rootFolder = new File(attachmentRootFolder);
    if (!rootFolder.exists()) {
      rootFolder.mkdirs();
    }
    return attachmentRootFolder;
  }

  /**
   *
   * @param dmsFileNames
   * @return
   */
  public List getDmsDocumentAttachment(String dmsFileNames){

    List resultList = new ArrayList();
    FormFileAttachment attachment = null;
    InputStream inputStream = null;

      String[] fileNameArray = TextUtility.splitString(dmsFileNames,";");

      for (int i=0; i<fileNameArray.length; i++) {
        String[] arrName = TextUtility.splitString(fileNameArray[i],":");

        String externalID = arrName[0];
        String fileName = arrName[1];
        String contentSize = arrName[2];
        externalID = externalID.substring(1,externalID.length()-1);
        fileName = fileName.substring(1,fileName.length()-1);
        //contentSize = contentSize.substring(1,contentSize.length()-1);
        contentSize = contentSize.substring(1,contentSize.lastIndexOf(']'));
        attachment = new FormFileAttachment();
        attachment.setAttachmentName(fileName);
        attachment.setExternalID(externalID);
        attachment.setFlowType(WorkflowProgressAttachment.ATTACHED_SINGLE_FILE);
        //attachment.setDataStream(inputStream);
        attachment.setContentSize(new Integer(contentSize));
        attachment.setAttachmentType(WorkflowProgressAttachment.ATTACHED_DMS_VERSION_SYSTEM_ID);
        resultList.add(attachment);
      }

      return resultList;

  }

  public void createFormFileAttachments(List attachmentList, Integer formDataElementID ) throws ApplicationException {
    if (attachmentList == null) {
      return;
    }

    FormFileAttachmentDAObject formFileAttachmentDAO = new FormFileAttachmentDAObject(this.sessionCon, this.dbConn);
    for (int i=0; i <attachmentList.size(); i++) {
      FormFileAttachment formFileAttachment = (FormFileAttachment) attachmentList.get(i);
      formFileAttachment.setFormDataElementID(formDataElementID);
      //* insert the record
      formFileAttachmentDAO.insertObject(formFileAttachment);

      //* if the type is single attachment, need to store the file to the server
      if ( WorkflowProgressAttachment.ATTACHED_SINGLE_FILE.equals(formFileAttachment.getAttachmentType()) ) {
        WorkflowContentStoreHandler contentStoreHandler = null;
        try {
          contentStoreHandler = (WorkflowContentStoreHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.WORKFLOW_CONTENT_STORE_CLASS)).newInstance();
        } catch (Exception e) {
          throw new ApplicationException(WorkflowErrorConstant.CONTENT_HANDLER_CLASS_NOT_FOUND);
        }
        contentStoreHandler.setProperty(WorkflowContentStoreHandler.FILE_PHYSICAL_PATH, this.getStorageLocation()+"/");
        contentStoreHandler.setProperty(WorkflowContentStoreHandler.FILE_NAME_PROPERTY, formFileAttachment.getExternalID());
        contentStoreHandler.setProperty(WorkflowContentStoreHandler.FILE_CONTENT_PROPERTY, formFileAttachment.getDataStream());
        contentStoreHandler.write();
        contentStoreHandler.close();
      }
    }
  }

  /**
   * getDataInputStreamByAttachment - Get a input stream of the file content pointed by the form file progress attachment record supplied.
   *
   * @param attachment     form file attachment record
   * @return               the input stream of the form file attachment file
   * @throws ApplicationException
   */
  public InputStream getDataInputStreamByAttachment(FormFileAttachment attachment) throws ApplicationException {
    InputStream dataStream = null;
    WorkflowOperationManager wfOperationManager = new WorkflowOperationManager(sessionCon, dbConn);

    String attachmentType = attachment.getAttachmentType();
    if (WorkflowProgressAttachment.ATTACHED_SINGLE_FILE.equals(attachmentType) || WorkflowProgressAttachment.ATTACHED_NEW_CHECK_IN_DOCUMENT.equals(attachmentType)) {
      WorkflowContentStoreHandler contentStoreHandler = null;
      try {
        contentStoreHandler = (WorkflowContentStoreHandler)Class.forName(SystemParameterFactory.getSystemParameter(SystemParameterConstant.WORKFLOW_CONTENT_STORE_CLASS)).newInstance();
      } catch (Exception e) {
        throw new ApplicationException(WorkflowErrorConstant.CONTENT_HANDLER_CLASS_NOT_FOUND);
      }
      contentStoreHandler.setProperty(WorkflowContentStoreHandler.FILE_NAME_PROPERTY, attachment.getExternalID());
      String attachmentRootFolder = this.getStorageLocation() + "/";
      contentStoreHandler.setProperty(WorkflowContentStoreHandler.FILE_PHYSICAL_PATH, attachmentRootFolder);
      dataStream = contentStoreHandler.readStream();
    }

    return dataStream;
  }

  /**
   * getFormFileAttachment - Get the form file attachment
   *
   * @param progressID     attachment id
   * @return               workflow progress attachment
   * @throws ApplicationException
   */
  public FormFileAttachment getFormFileAttachment(Integer attachmentID) throws ApplicationException {
    FormFileAttachmentDAObject attachmentDAO = new FormFileAttachmentDAObject (sessionCon, dbConn);
    return (FormFileAttachment)attachmentDAO.getObjectByID(attachmentID);
  }

  /**
   * getFormFileAttachmentWithContent - Get the Form File attachment, with the content of attachment returned also
   *
   * @param progressID     attachment id
   * @return               Form File attachment
   * @throws ApplicationException
   */
  public FormFileAttachment getFormFileAttachmentWithContent(Integer attachmentID) throws ApplicationException {
    FormFileAttachment formFileAttachment = this.getFormFileAttachment(attachmentID);

    InputStream dataStream = this.getDataInputStreamByAttachment(formFileAttachment);
    formFileAttachment.setDataStream(dataStream);

    return formFileAttachment;
  }

  /**
   * get form page permission.
   * @param formRecordID
   * @param formPageID
   * @param workflowStepID
   * @return
   * @throws ApplicationException
   */
  public boolean getFormPagePermissionByRecordPageIDStepID(Integer formRecordID, Integer formPageID, Integer workflowStepID,boolean isViewUserStep) throws ApplicationException {
    boolean hasPermission = false;
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    hasPermission = formPageDAO.getFormPagePermissionByRecordIDPageIDStepID(formRecordID,formPageID,workflowStepID,isViewUserStep);
    return hasPermission;
  }

  /**
   * get form section permission.
   * @param formRecordID
   * @param formPageID
   * @param formSectionID
   * @param workflowStepID
   * @return
   * @throws ApplicationException
   */
  public boolean getFormSectionPermissionByRecordPageIDSectionIDStepID(Integer formRecordID, Integer formPageID, Integer formSectionID, Integer workflowStepID,boolean isViewUserStep) throws ApplicationException {
    boolean hasPermission = false;
    FormSectionDAObject formSectionDAO = new FormSectionDAObject(this.sessionCon,this.dbConn);
    hasPermission = formSectionDAO.getFormSectionPermissionByRecordIDPageIDSectionIDStepID(formRecordID,formPageID,formSectionID,workflowStepID,isViewUserStep);
    return hasPermission;
  }


  /**
   * check the element in a form.
   * @param formRecordID
   * @return
   * @throws ApplicationException
   */
  public boolean hasElement(String formRecordID) throws ApplicationException {
    boolean hasElement = false;
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    if (!Utility.isEmpty(formRecordID) && !"null".equals(formRecordID)){
      List formPageList = formPageDAO.getDetailListByFormRecordID(new Integer(formRecordID));
      for (int j = 0; j < formPageList.size(); j++){
        FormPage formPage =(FormPage)formPageList.get(j);
        List formSectionList = formPage.getFormSectionList();
        for (int n = 0; n < formSectionList.size(); n++ ){
          FormSection formSection = (FormSection)formSectionList.get(n);
          List formElementList = formSection.getFormElementList();
          if (formElementList.size()>0){
            hasElement = true;
            break;
          }
        }
      }
    }
    return hasElement;
  }

  public List getSubmissionElementListByFormRecordIDWfRecordID(String formRecordID, String workflowRecordID, String formElementType) throws ApplicationException {
    List result = new ArrayList();
    Integer workflowStepID = new Integer(0);
    Integer pageID,sectionID,elementID;
    String formRecordPermission,pagePermission,sectionPermission,elementPermission;
    //get DAO
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionCon,this.dbConn);
    FormRecordDAObject formRecordDAO =  new FormRecordDAObject(this.sessionCon,this.dbConn);
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);

    if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
      WorkflowStep workflowStep = (WorkflowStep)workflowStepDAO.getSubmitStepByWorkflowRecordID(new Integer(workflowRecordID));
      workflowStepID = workflowStep.getID();

      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(new Integer(formRecordID),workflowStepID);
      for (int pp=0; pp<formPageList.size(); pp++){
        FormPage formPage = (FormPage)formPageList.get(pp);
        pageID = formPage.getID();
        formRecordPermission = formPage.getFormRecordPermission();
        if (!Utility.isEmpty(formPage.getPermission())){
          pagePermission = formPage.getPermission();
        }else {
          pagePermission = formRecordPermission;
        }
        List formSectionList = formPage.getFormSectionList();
        for (int i=0; i<formSectionList.size(); i++) {
          FormSection tmpFormSection = (FormSection) formSectionList.get(i);
          if (!Utility.isEmpty(tmpFormSection.getPermission())){
            sectionPermission = tmpFormSection.getPermission();
          }else {
            sectionPermission = pagePermission;
          }
          List formElementList = tmpFormSection.getFormElementList();
          for (int j=0; j<formElementList.size(); j++) {
            FormElement tmpFormElement = (FormElement) formElementList.get(j);
            if (!Utility.isEmpty(tmpFormElement.getPermission())){
              elementPermission = tmpFormElement.getPermission();
            }else {
              elementPermission = sectionPermission;
            }
            if (hasPermissionShowFormElement(elementPermission) ){
              if (Utility.isEmpty(formElementType) || "null".equals(formElementType)){
                result.add(tmpFormElement);
              }else if (FormElementType.ELEMENT_DATE_PICKER.equals(formElementType) && tmpFormElement.getElementType().equals(formElementType)){
                result.add(tmpFormElement);
              }else if (FormElementType.isSelection(formElementType) && tmpFormElement.getElementType().equals(formElementType)){
                result.add(tmpFormElement);
              }else if (FormElementType.ELEMENT_TEXT.equals(formElementType) && tmpFormElement.getElementType().equals(formElementType)){
                result.add(tmpFormElement);
              }
            }
          }
        }
      }
    }else if (!Utility.isEmpty(formElementType) && !"null".equals(formElementType)){
      result = formRecordDAO.getSearchElementListByFormRecordIDElementType(new Integer(formRecordID),formElementType);
    }else{
      result = formRecordDAO.getSearchElementListByFormRecordID(new Integer(formRecordID));
    }

    return result;
  }

  /**
   * @param elementPermission
   * @return
   */
  private boolean hasPermissionShowFormElement(String elementPermission) {
    return WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE.equals(elementPermission)
        || WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(elementPermission)
        || WorkflowStep.FORM_PROCESS_PERMISSION_READ.equals(elementPermission)
        || WorkflowStep.FORM_PROCESS_PERMISSION_INHERIT.equals(elementPermission);
  }

  public List getRelatedItemListByFormRecordID(String formRecordID) throws ApplicationException {
    List result = new ArrayList();
    FormRecordDAObject formRecordDAO =  new FormRecordDAObject(this.sessionCon,this.dbConn);
    result = formRecordDAO.getRelatedItemListByFormRecordID(new Integer(formRecordID));
    return result;
  }

  public List getSearchElementListByWorkflowRecordIDFormRecordIDUserRecordID(Integer workflowRecordID, Integer formRecordID, Integer userRecordID) throws ApplicationException {
    List result = new ArrayList();
    Integer workflowStepID = new Integer(0);
    Integer pageID,sectionID,elementID;
    String formRecordPermission,pagePermission,sectionPermission,elementPermission;
    //get DAO
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionCon,this.dbConn);
    FormRecordDAObject formRecordDAO =  new FormRecordDAObject(this.sessionCon,this.dbConn);
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);

    if (!Utility.isEmpty(workflowRecordID) && !"null".equals(workflowRecordID)){
      List stepList = workflowStepDAO.getStepListByWorkflowRecordIDFormRecordIDUserRecordID(workflowRecordID, formRecordID, userRecordID);
      for (int n=0; n<stepList.size(); n++){
        WorkflowStep workflowStep = (WorkflowStep)stepList.get(n);
        workflowStepID = workflowStep.getID();
        List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(formRecordID,workflowStepID);
        for (int pp=0; pp<formPageList.size(); pp++){
          FormPage formPage = (FormPage)formPageList.get(pp);
          pageID = formPage.getID();
          formRecordPermission = formPage.getFormRecordPermission();
          if (!Utility.isEmpty(formPage.getPermission())){
            pagePermission = formPage.getPermission();
          }else {
            pagePermission = formRecordPermission;
          }
          List formSectionList = formPage.getFormSectionList();
          for (int i=0; i<formSectionList.size(); i++) {
            FormSection tmpFormSection = (FormSection) formSectionList.get(i);
            if (!Utility.isEmpty(tmpFormSection.getPermission())){
              sectionPermission = tmpFormSection.getPermission();
            }else {
              sectionPermission = pagePermission;
            }
            List formElementList = tmpFormSection.getFormElementList();
            for (int j=0; j<formElementList.size(); j++) {
              FormElement tmpFormElement = (FormElement) formElementList.get(j);
              if (!Utility.isEmpty(tmpFormElement.getPermission())){
                elementPermission = tmpFormElement.getPermission();
              }else {
                elementPermission = sectionPermission;
              }
              if (hasPermissionShowFormElement(elementPermission) ){
                if (!result.contains(tmpFormElement)){
                  result.add(tmpFormElement);
                }
              }
            }
          }
        }
      }
    }else{
      result = formRecordDAO.getSearchElementListByFormRecordID(formRecordID);
    }
    return result;
  }

  public void createElementTD(PageContext pageContext,FormElement tmpFormElement,FormAttach formAttach, HttpServletRequest request,JspWriter out,String elementValue,List attachmentList, AbstractActionForm abstractActionForm,Integer pageID,Integer sectionID, boolean hasCheckPermission, boolean isStepElementChange, boolean isStepElementRead, SysFunction sysFunction,String onchangeElementIDStr,boolean isAuditColor,String currentFormSubmissionStatus){
    try{
      String maintForm = abstractActionForm instanceof MaintFormSubmissionForm ? "maintFormSubmissionForm" : "maintFormSectionForm";
      //String FIELD_HEADER = "FB_FIELD_";
      //String fieldName = FIELD_HEADER+pageID+"_"+sectionID+"_"+sectionSeq+"_"+tmpFormElement.getRowIndex()+"_"+tmpFormElement.getID()+"_"+elementSeq;
      String fieldName = getFieldName(tmpFormElement,pageID,sectionID);
      //String preFieldName = FIELD_HEADER+pageID+"_"+sectionID+"_"+preSectionSeq+"_"+tmpFormElement.getRowIndex()+"_"+tmpFormElement.getID()+"_"+elementSeq;
      String preFieldName = getFieldName(tmpFormElement,pageID,sectionID);
      String fieldValue = request.getParameter(preFieldName);
      java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
      String navMode = abstractActionForm.getNavMode();
      String opMode = abstractActionForm.getOpMode();
      String value;
      String elementAlign = "left"; // default align left.
      String formSubmissionID = request.getParameter("formSubmissionID");
      if ("null".equals(formSubmissionID)) {
        formSubmissionID = "";
      }
      Integer fontSize;
      String fontColor = "";
      String fontStyle = "";
      String labelPosition = "";
      String fontType = "";
      String preFontStyle = "<font ";        //Prefix  FontStyle
      String posFontStyle = "</font>";       //Postfix FontStyle
      String nextFontStyle = "";
      String leftPosition = "";
      String topPosition = "";
      String fileHideName = "";
      String onchangeElementID = ""; //routing rule
      String targetElement = "";
      String auditColor = "#0000FF";
      fontSize = tmpFormElement.getFontSize();
      fontColor = tmpFormElement.getFontColor();
      fontStyle = tmpFormElement.getFontStyle();
      fontType = tmpFormElement.getFontType();
      labelPosition = tmpFormElement.getLabelPosition();

      if(!Utility.isEmpty(fontStyle) || !Utility.isEmpty(fontSize) ||
          !Utility.isEmpty(fontColor) || !Utility.isEmpty(fontType)){
        preFontStyle += " style='";
      }

      //handel Font Style
      if (!Utility.isEmpty(fontStyle)) {
        //preFontStyle += " style='";
        for (int k=0; k < fontStyle.length(); k++) {
          if ("B".equals(fontStyle.substring(k,k+1))) {
            preFontStyle += "font-weight: bold;";
          } else if ("U".equals(fontStyle.substring(k,k+1))) {
            preFontStyle += "text-decoration: underline;";
          } else if ("I".equals(fontStyle.substring(k,k+1))) {
            preFontStyle += "font-style: italic;";
          }
        }
      }

      if (!Utility.isEmpty(fontSize)) {
        preFontStyle += " font-size:" + fontSize+"pt;";
      }
      if (!Utility.isEmpty(fontColor)) {
        preFontStyle += " color:" + fontColor+";";
      }
      if (!Utility.isEmpty(fontType)) {
        preFontStyle += " font-family:" +
        MessageResourcesFactory.getMessage(sessionCon.getSessionLocale(), "form.label.element_fonts_"+fontType) +";";
      }
      if(preFontStyle.indexOf("'") >-1) {
        preFontStyle += "'";
      }
      preFontStyle += ">";
      if (preFontStyle.length() < 10) { // if not set the FontStyle of the element
        preFontStyle = "";
        posFontStyle = "";
      }
      if (!Utility.isEmpty(labelPosition)) {
        if (tmpFormElement.isLeftLabelPosition(labelPosition)) {
          elementAlign = "left";
          leftPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "";
        } else if (tmpFormElement.isCenterLabelPosition(labelPosition)) {
          elementAlign = "center";
          leftPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "";
        } else if (tmpFormElement.isRightLabelPosition(labelPosition)) {
          elementAlign = "right";
          leftPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "";
        } else if (tmpFormElement.isTopLabelPosition(labelPosition)) {
          topPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "<br>";
        } else if (tmpFormElement.isHiddenLabelPosition(labelPosition)){
          leftPosition = "";
          topPosition = "";
        } else {
            leftPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "";
        }
      } else {
        leftPosition = preFontStyle + tmpFormElement.getFieldName() + posFontStyle + "";
      }

      if(!Utility.isEmpty(fieldValue) && !"null".equals(fieldValue)) {
        value = TextUtility.htmlEncode(fieldValue);
      }else{
        value = TextUtility.htmlEncode(elementValue);
      }
      if(!Utility.isEmpty(fieldValue) && !"null".equals(fieldValue)) {
        fieldValue = fieldValue;
      }else{
        fieldValue = TextUtility.noNull(tmpFormElement.getDefaultValue());
      }
      //log.debug(fieldValue);
      if (GlobalConstant.NAV_MODE_EDIT.equals(navMode )){
        elementValue = value;
      }else if (GlobalConstant.NAV_MODE_NEW.equals(navMode ) || "T".equals(request.getParameter("preview")) ){
        elementValue = fieldValue;
      }else if (GlobalConstant.NAV_MODE_VIEW.equals(navMode) && GlobalConstant.OP_MODE_DELETE.equals(opMode)){
        elementValue = fieldValue;
      } else if (GlobalConstant.NAV_MODE_CHANGE.equals(navMode)) {
        elementValue = value;
      }

      if(FormElementType.isLabel(tmpFormElement.getElementType())){
        out.println("<td nowrap  colspan='2'  align='"+elementAlign+"' width='21%' class='greyD'>");
      }else{
        out.println("<td nowrap  align='"+elementAlign+"' width='21%' class='greyD'>");
      }
      String [] bindWFFormPermission = this.getBindWFFormPermission(request, abstractActionForm, pageID, sectionID,tmpFormElement);
      if(GlobalConstant.TRUE.equals(this.isMandatoryBindWFStep(request, abstractActionForm, pageID, sectionID,tmpFormElement))||("Y".equals(tmpFormElement.getRequiredFlag()) &&!"C".equals(bindWFFormPermission[3]))){
        out.write("<font color='red'>*</font>");
      }else{
        out.write("&nbsp;");
      }
      if (isAuditColor){
            out.print("<font color='"+auditColor+"' >");
        }
      //START TEXT BOX
      if(FormElementType.ELEMENT_TEXT.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
          out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
        }else{
            out.println("</td><td class='greyD'>"+topPosition);
        }

        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          if (!Utility.isEmpty(onchangeElementIDStr) && !"null".equals(onchangeElementIDStr) ){
            String[] elementIDArr = TextUtility.splitString(onchangeElementIDStr,"$");
            targetElement = elementIDArr[0];
            String[] elementNameArr = TextUtility.splitString(elementIDArr[1],"|");
            for (int nn=0; nn<elementNameArr.length; nn++){
              String[] tmpPageSectionElementArr = TextUtility.splitString(elementNameArr[nn],"_");
              if(tmpPageSectionElementArr[4].equals(tmpFormElement.getID().toString())){
                onchangeElementID = tmpPageSectionElementArr[4];
              }
            }
          }
          out.println("<input type='text' name='"+fieldName+"' value='"+elementValue+"' size='"+tmpFormElement.getWidth()+"' maxlength='200' ");
          if (!"T".equals(request.getParameter("preview"))){
            if(onchangeElementID.equals(tmpFormElement.getID().toString())){
              out.println("onchange='opChangeElement_"+targetElement+"()'/>");
            }else{
              out.println("/>");
            }
          }else{
            out.println("/>");
          }


        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange) {
          if((!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode))||Utility.isEmpty(elementValue) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
            out.print(elementValue);
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
            out.print("</font>");
          }
      }

      //START CURRENT LOGIN
      else if(FormElementType.ELEMENT_CURRENT_LOGIN.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
          out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
        }else{
          out.println("</td><td class='greyD'>"+topPosition);
        }
        /*if ("T".equals(request.getParameter("preview"))){
          out.println("<input type='text' name='"+fieldName+"' />");
        }else*/ if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode) ) {
          if (!"FORMMONITOR".equals(request.getParameter("function"))){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+sessionCon.getUserRecord().getFullName()+"' />");
            out.print(sessionCon.getUserRecord().getFullName());
          }else{
            out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
            out.print(!Utility.isEmpty(elementValue)? elementValue : "");
          }
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange) {
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
            out.print(!Utility.isEmpty(elementValue)? elementValue : "");
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END CURRENT LOGIN
      //START CURRENT DATE

      else if(FormElementType.ELEMENT_CURRENT_DATE.equals(tmpFormElement.getElementType())){
        String currentDate = (Utility.getCurrentTimestamp().toString()).substring(0,10);
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        /*if ("T".equals(request.getParameter("preview"))){
          out.println("<input type='text' name='"+fieldName+"' />");
        }else*/ if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          if (!"FORMMONITOR".equals(request.getParameter("function"))){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+currentDate+"' />");
            out.print(currentDate);
          }else{
            out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
            out.print(!Utility.isEmpty(elementValue)? elementValue : "");
          }
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange) {
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
            out.print((!Utility.isEmpty(elementValue)) ? elementValue : "");
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }

      //END CURRENT DATE
      //START TEXT AREA

      else if(FormElementType.ELEMENT_TEXT_AREA.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<textarea name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' rows='"+tmpFormElement.getHeight()+"' cols='"+tmpFormElement.getWidth()+"' onkeydown='CheckTextArea(this, 1300);' onkeyup='CheckTextArea(this, 1300);'>"+elementValue+"</textarea>");
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
          if((!Utility.isEmpty(formSubmissionID)&& !GlobalConstant.OP_MODE_UPDATE.equals(opMode))||Utility.isEmpty(elementValue) ){
             out.print(elementValue);
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue );
            }
          }
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END TEXT AREA

      //START LABEL

      else if(FormElementType.isLabel(tmpFormElement.getElementType())){
        out.println(preFontStyle+tmpFormElement.getFieldName()+posFontStyle+"</td><td class='greyD'>");
      }
      //END LABEL

      //START PASSWORD

      else if(FormElementType.ELEMENT_PASSWORD.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='password' name='"+fieldName+"' value='"+elementValue+"' size='"+tmpFormElement.getWidth()+"' maxlength='200'/>");
        } else if ((isStepElementRead || isStepElementChange)&&!Utility.isEmpty(elementValue) ) {
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
          out.println("********************");
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END PASSWORD

      //START SIGNATURE
      else if(FormElementType.ELEMENT_SIGNATURE.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='text' name='"+fieldName+"' value='"+elementValue+"' size='"+tmpFormElement.getWidth()+"' maxlength='200' />");
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange) {
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
            out.print(elementValue);
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END SIGNATURE

      //START CONDITIONID
      if(FormElementType.ELEMENT_CONDITIONAL_FIELD.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='text' name='"+fieldName+"' value='"+elementValue+"' size='"+tmpFormElement.getWidth()+"' maxlength='200' ");
          out.println("onchange='"+FormConstant.FORM_DB_LOOKUP_FUNCTION_NAME+"("+tmpFormElement.getID()+","+fieldName+")'/>");
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
            out.print(elementValue);
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //CONDITIONID END

      //START IMAGE
      else if (FormElementType.ELEMENT_IMAGE.equals(tmpFormElement.getElementType())) {
        String imageName="";
        String  repath=SystemParameterFactory.getSystemParameter(SystemParameterConstant.FORM_ATTACHMENT_PHYSICAL_PATH);
        if (formAttach!=null) {
          imageName=formAttach.getFileName();
        } else {
          imageName="";
        }

        if (tmpFormElement.isLeftLabelPosition(labelPosition) || Utility.isEmpty(labelPosition) || "null".equals("labelPosition")){
          out.println(preFontStyle+tmpFormElement.getFieldName()+posFontStyle);
        }
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if (tmpFormElement.isTopLabelPosition(labelPosition) ) {
          out.println("<table><tr><td> "+preFontStyle+tmpFormElement.getFieldName()+posFontStyle+"</td></tr><tr><td>");
        }

        if (formAttach!=null) {
          if (imageName.indexOf(".")>0) {
            out.println("<img src='../jsp/form/IncludeShowImgFile.jsp?imageName="+repath+"/"+tmpFormElement.getID()+ imageName.substring(imageName.indexOf("."),imageName.length())+"'></td>");
          }
        }
        if (tmpFormElement.getLabelPosition()!=null) {
          if (tmpFormElement.isTopLabelPosition(labelPosition)){
            out.println("</td></tr></table>");
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END IMAGE

      //START DATEPICKER
      else if(FormElementType.ELEMENT_DATE_PICKER.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
          if(!Utility.isEmpty(elementValue)){
            elementValue = TextUtility.parseDBDateTime(elementValue);
            if (Utility.isEmpty(elementValue)) {
              elementValue = "";
            }
          } else{
            elementValue = "";
          }
          out.println("<input type='text' name='"+"dummy_"+fieldName+"' value='"+elementValue+"' maxlength='10' size='10' onblur=\"return (fcheck_date(this, '"+SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATETIME_FORMAT).substring(0,10).toLowerCase()+"'))\"/>");
          if("T".equals(request.getParameter("preview"))){
            out.println("<img src='"+WebUtil.getImage(request, "IconCalendar.gif")+"' name='imgCalendar_"+fieldName+"' align='absmiddle' width='34' height='21' border='0' alt=''/>");
          }
          else{
            out.println(" <a href='javascript:void(0);' onmouseover='if (timeoutId) clearTimeout(timeoutId);window.status=\"Show Calendar\";return true;' onclick='gfPop.fPopCalendar(document."+maintForm+".dummy_"+fieldName+",document."+maintForm+"."+fieldName+",depRange,false,\""+SystemParameterFactory.getSystemParameter(SystemParameterConstant.DATETIME_FORMAT).substring(0,10).toLowerCase()+"\",true);'>");
            out.println("<img src='"+WebUtil.getImage(request, "IconCalendar.gif")+"' name='imgCalendar_"+fieldName+"' align='absmiddle' width='34' height='21' border='0' alt=''/></a>");
          }



        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.print((Utility.isEmpty(elementValue)||"null".equals(elementValue))?"":elementValue.substring(0,10));
          } else {
            out.print(Utility.isEmpty(fieldValue)?"":fieldValue.substring(0,10));
          }
          out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
          out.println("<input type='hidden' name='dummy_"+fieldName+"' value='"+elementValue+"' />");
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END DATEPICKER

      //START TIMEPICKER

      else if(FormElementType.ELEMENT_TIME_PICKER.equals(tmpFormElement.getElementType())){
        String sFieldID = pageID+"_"+sectionID+"_"+tmpFormElement.getID();
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          int iHourPart = (!Utility.isEmpty(elementValue) && !"null".equals(elementValue))? new Integer(elementValue.substring(0,2)).intValue() : -1;
          int iMinutePart = (!Utility.isEmpty(elementValue) && !"null".equals(elementValue))? new Integer(elementValue.substring(3,5)).intValue() : -1;

          //hour selection box
          out.print("<select name='"+"TIME_HOUR_"+sFieldID+"' ");
          out.print("onchange=\"getOntimechange(\'"+sFieldID+"\')\" ");
          out.println(">");
          for (int i=0; i<24; i++) {
            out.print("  <option value=\""+(i<10? ("0"+i): Integer.toString(i))+"\" "+(iHourPart==i? "selected": "")+">"+(i<10? ("0"+i): Integer.toString(i))+"</option>");
          }
          out.println("</select>");

          out.println(":");

          //minute selection box
          out.print("<select name='"+"TIME_MIN_"+sFieldID+"'");
          out.print("onchange=\"getOntimechange(\'"+sFieldID+"\')\" ");
          out.println(">");
          for (int i=0; i<60; i++) {
            out.print("  <option value=\""+(i<10? ("0"+i): Integer.toString(i))+"\" "+(iMinutePart==i? "selected": "")+">"+(i<10? ("0"+i): Integer.toString(i))+"</option>");
          }
          out.println("</select>");
          out.println("<input type='hidden' name='"+fieldName+"' value='"+elementValue+"' />");
        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.print((Utility.isEmpty(elementValue)||"null".equals(elementValue))?"":elementValue);
          } else {
            out.print(Utility.isEmpty(fieldValue)?"":fieldValue);
          }
        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END TIMEPICKER

      //BEGIN USER PICKER
      else if(FormElementType.ELEMENT_USER_PICKER.equals(tmpFormElement.getElementType())){
        out.println(leftPosition);
    if (isAuditColor){
        out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
      }else{
        out.println("</td><td class='greyD'>"+topPosition);
      }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='text' name='"+"dummy_"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' onkeydown='return false;' onkeypress='return false;' />");
          out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
          if("T".equals(request.getParameter("preview"))){
            out.println("<img src='"+WebUtil.getImage(request, "IconSearchUser.gif")+"' name='imgCalendar_"+fieldName+"' align='absmiddle' border='0' alt=''/>");
          }
          else{
            out.println(" <a href='javascript:void(0);' onclick='return OpenCenteredPopup(\"../user/PopupUserRecord.do?mode=L&property="+fieldName+"&form="+maintForm+"\",\"DCIVisionPopupUser\", 700, 500, \"scrollbars=yes,resizable=yes\");'>");
            out.println("<img src='"+WebUtil.getImage(request, "IconSearchUser.gif")+"' name='imgCalendar_"+fieldName+"' align='absmiddle' border='0' alt=''/></a>");
          }


        } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
          if(!Utility.isEmpty(formSubmissionID) && !GlobalConstant.OP_MODE_UPDATE.equals(opMode) ){
            out.println("<input type='hidden' name='"+fieldName+"' value='"+TextUtility.htmlEncode(elementValue)+"' />");
            out.print(elementValue);
          } else {
            if(!Utility.isEmpty(fieldValue)) {
              out.print(fieldValue);
            }
          }
        }
        if (isAuditColor){
        out.print("</font>");
      }
      }

      //START FILE BOX
      else if(FormElementType.ELEMENT_FILE.equals(tmpFormElement.getElementType())){
        fileHideName = pageID+"_"+sectionID+"_"+tmpFormElement.getID();
        int normalFileCount = 0,dmsFileCount = 0;
        String versionID = "";
        String fileNames = "",displayFileNames = "",dmsFileNames = "", displayDmsFileNames = "";
        out.println(leftPosition);
        if (isAuditColor){
            out.println("</font></td><td class='greyD'>"+topPosition+"<font color='"+auditColor+"' >");
          }else{
            out.println("</td><td class='greyD'>"+topPosition);
          }
        if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
          out.println("<input type='hidden' name='"+"fileNames_"+fileHideName+"' value='"+request.getParameter("fileNames_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"dmsFileNames_"+fileHideName+"' value='"+request.getParameter("displayFileNames_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"displayFileNames_"+fileHideName+"' value='"+request.getParameter("fileNames_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"displayDmsFileNames_"+fileHideName+"' value='"+request.getParameter("displayDmsFileNames_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"FB_FILES_"+fileHideName+"' value='"+request.getParameter("oldUpdateFileText_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"oldUpdateFileText_"+fileHideName+"' value='"+request.getParameter("fileNames_"+fileHideName)+"'/>");
          out.println("<input type='hidden' name='"+"oldUpdateFileValue_"+fileHideName+"'value='"+request.getParameter("oldUpdateFileValue_"+fileHideName)+"'/>");
          out.println("<span id='"+"attachmentDiv_"+fileHideName+"' style='display:block;float:left;width:200px;height:25px;overflow:auto;background-color:#FFFFFF;layer-background-color:#FFFFFF;border-style:inset;border-width:1px;'></span>");
          out.println("<script language='javaScript'>redrawAttachmentPanel('"+fileHideName+"');</script>");
          if ( sysFunction!=null && GlobalConstant.STATUS_ACTIVE.equals(sysFunction.getStatus()) ){
            PermissionManager permissionManager = sessionCon.getPermissionManager();
            Integer DMS_PERSONAL_FOLDER = new Integer("6001");
            Integer DMS_PUBLIC_FOLDER = new Integer("6002");
            String permissionStr = permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_FUNCTION,DMS_PERSONAL_FOLDER);
            permissionStr += permissionManager.getPermission(GlobalConstant.OBJECT_TYPE_FUNCTION,DMS_PUBLIC_FOLDER);
            if(!Utility.isEmpty(permissionStr) && permissionStr.indexOf("R") > -1 ){
              if ("T".equals(request.getParameter("preview"))){
               
                out.println(TagUtil.renderStandardButton(pageContext,"upload.label.uploadattachement","return(false)",null));
              }else{
               
                StandardButtonTag button = new StandardButtonTag();
                button.setPageContext(pageContext);
                button.setLabel("upload.label.uploadattachement");
                button.setOnClick("return OpenCenteredPopup('../upload/ListLookupFromParaDoc.do?navMode=V&fileNameSeqNo="+fileHideName+"&SHOW_HEADER_FOOTER=N', 'attachmentDiv', '800', '650', 'scrollbars=yes')");
                button.setOnmouseover("if (timeoutId) clearTimeout(timeoutId);window.status='Show Upload File';return true;");
                out.println(TagUtil.renderTag(pageContext, button));
               
              }
            }else{
              if ("T".equals(request.getParameter("preview")) ){
             
                out.println(TagUtil.renderStandardButton(pageContext,"upload.label.uploadattachement","return(false)",null));
              }else{
                
                StandardButtonTag button = new StandardButtonTag();
                button.setPageContext(pageContext);
                button.setLabel("upload.label.uploadattachement");
                button.setOnClick("return OpenCenteredPopup('../upload/MaintMultipleFileUpload.do?navMode=V&fileNameSeqNo="+fileHideName+"&SHOW_HEADER_FOOTER=N', 'attachmentDiv', '800', '650', null)");
                button.setOnmouseover("if (timeoutId) clearTimeout(timeoutId);window.status='Show Upload File';return true;");
                out.println(TagUtil.renderTag(pageContext, button));
                
              }
            }
          }else{
            if ("T".equals(request.getParameter("preview")) ){
              
              out.println(TagUtil.renderStandardButton(pageContext,"upload.label.uploadattachement","return(false)",null));
            }else{
             
              StandardButtonTag button = new StandardButtonTag();
              button.setPageContext(pageContext);
              button.setLabel("upload.label.uploadattachement");
              button.setOnClick("return OpenCenteredPopup('../upload/MaintMultipleFileUpload.do?navMode=V&fileNameSeqNo="+fileHideName+"&SHOW_HEADER_FOOTER=N', 'attachmentDiv', '800', '650', null)");
              button.setOnmouseover("if (timeoutId) clearTimeout(timeoutId);window.status='Show Upload File';return true;");
              out.println(TagUtil.renderTag(pageContext, button));
              
            }
          }
          for (int i=0; i<attachmentList.size(); i++) {
            FormFileAttachment attachment = (FormFileAttachment)attachmentList.get(i);

            if(WorkflowProgressAttachment.ATTACHED_DMS_VERSION_SYSTEM_ID.equals(attachment.getAttachmentType()) ){
              dmsFileCount++;
              versionID = attachment.getExternalID();
              dmsFileNames += "[" + versionID + "]:[" + attachment.getAttachmentName() + "]:[" + attachment.getContentSize() + "];";
              displayDmsFileNames += attachment.getAttachmentName() + ";" ;

              DmsVersionDAObject dmsVersionDAO = new DmsVersionDAObject(sessionCon, dbConn);
              DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionCon, dbConn);

              DmsVersion dmsVersion = (DmsVersion)dmsVersionDAO.getObjectByID(new Integer(versionID));
              Integer dmsDocumentID = dmsVersion.getDocumentID();

              out.println("<a href='../dms/FileDownloadServlet?sCurFunctionCode=DMS_PUBLIC_FOLDER&targetID="+dmsDocumentID+"&documentType=D&version=TOP&ext=.HTM' target='_blank'>");
              out.println("<img src='"+WebUtil.getImage(request, "IconFile.gif")+"' align='absmiddle' border='0' />");
              out.println(attachment.getAttachmentName()+"</a>");


            } else if (!Utility.isEmpty(attachment.getExternalID())) {
              normalFileCount ++;
              fileNames += attachment.getAttachmentName() + ":" + attachment.getExternalID() + "|" ;
              displayFileNames += attachment.getAttachmentName() + ";" ;

              out.println("<a href='GetFormFileAttachmentServlet?ID="+attachment.getID()+"' target='_blank'><img src='"+WebUtil.getImage(request, "IconFile.gif")+"' align='absmiddle' border='0' />");
              out.println(attachment.getAttachmentName()+"</a>");

            }
          }

          if (dmsFileCount>0 || (!Utility.isEmpty(request.getParameter("dmsFileNames_"+fileHideName)) && !"null".equals(request.getParameter("dmsFileNames_"+fileHideName)) )){
            if (!Utility.isEmpty(request.getParameter("dmsFileNames_"+fileHideName)) && !"null".equals(request.getParameter("dmsFileNames_"+fileHideName)) ){
              dmsFileNames = request.getParameter("dmsFileNames_"+fileHideName);
            }
            out.println("<script language='javaScript'>setDmsFileNamesValue('"+displayDmsFileNames+"','"+dmsFileNames+"','"+fileHideName+"');</script>");
          }
          if (normalFileCount>0 || (!Utility.isEmpty(request.getParameter("fileNames_"+fileHideName)) && !"null".equals(request.getParameter("fileNames_"+fileHideName)) ) ){
            if (!Utility.isEmpty(request.getParameter("fileNames_"+fileHideName)) && !"null".equals(request.getParameter("fileNames_"+fileHideName)) ){
              fileNames = request.getParameter("fileNames_"+fileHideName);
            }else{
              fileNames = new Integer(normalFileCount).toString() + "|" + fileNames ;
            }
            out.println("<script language='javaScript'>PutFileNamesToForm('"+fileNames+"','"+displayFileNames+"','"+fileHideName+"');</script>");
          }
        }else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {

          for (int i=0; i<attachmentList.size(); i++) {

            FormFileAttachment attachment = (FormFileAttachment)attachmentList.get(i);
            if (WorkflowProgressAttachment.ATTACHED_DMS_VERSION_SYSTEM_ID.equals(attachment.getAttachmentType()) ){
              versionID = attachment.getExternalID();
              DmsVersionDAObject dmsVersionDAO = new DmsVersionDAObject(sessionCon, dbConn);
              DmsDocumentDAObject dmsDocumentDAO = new DmsDocumentDAObject(sessionCon, dbConn);
              DmsVersion dmsVersion = (DmsVersion)dmsVersionDAO.getObjectByID(new Integer(versionID));
              Integer dmsDocumentID = dmsVersion.getDocumentID();
              out.println("<a href='../dms/FileDownloadServlet?sCurFunctionCode=DMS_PUBLIC_FOLDER&targetID="+dmsDocumentID+"&documentType=D&version=TOP&ext=.HTM' target='_blank'>");
              out.println("<img src='"+WebUtil.getImage(request, "IconFile.gif")+"' align='absmiddle' border='0' />");
              out.println(attachment.getAttachmentName()+"</a>");

            } else if (!Utility.isEmpty(attachment.getExternalID())) {

              out.println("<a href='GetFormFileAttachmentServlet?ID="+attachment.getID()+"' target='_blank'><img src='"+WebUtil.getImage(request, "IconFile.gif")+"' align='absmiddle' border='0' />");
              out.println(attachment.getAttachmentName()+"</a>");

            }
          }

        }
        if (isAuditColor){
          out.print("</font>");
        }
      }
      //END FILE BOX

      //if the form element is selection type
      else if(FormElementType.isSelection(tmpFormElement.getElementType())){

        String selectedValue = "";
        FormSelectionField formSelectionField = tmpFormElement.getFormSelectionField();
        out.println(leftPosition);
        if (isAuditColor){
          out.println("</font>");
        }
        out.println("</td><td class='greyD'>"+topPosition);

        if(formSelectionField != null){
          String brString = "";
          final int rowSize=10;
          if (!Utility.isEmpty(formSelectionField.getDisplayType())) {
            brString = formSelectionField.isVertical(formSelectionField.getDisplayType())? "<br>":"";
          }
          List formSelectionFieldOptionList = formSelectionField.getFormSelectionFieldOptionList();
          for (int index=0; index<formSelectionFieldOptionList.size(); index++) {
            FormSelectionFieldOption tmpFormSelectionFieldOption = (FormSelectionFieldOption) formSelectionFieldOptionList.get(index);
            //bill add for EIP-1241 start
            String newline=null;
            if(index%rowSize==0&&index!=0){
                newline="<br>";
              }
           //bill add for EIP-1241 end

            //if the form element is a radio box

            //START RADIO BOX
            if(FormElementType.ELEMENT_RADIO_BUTTON.equals(tmpFormElement.getElementType())){
              out.println("<input type='radio' name='"+fieldName+"' value='"+tmpFormSelectionFieldOption.getStartValue()+"' ");
              if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
                // Use default value just in case specified element value is empty!
                if (Utility.isEmpty(elementValue) && !Utility.isEmpty(fieldValue) &&fieldValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" checked ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" checked ");
                }
              } else if (!hasCheckPermission || isStepElementRead || isStepElementChange ) {
                // Use default value just in case specified element value is empty!
                if (Utility.isEmpty(elementValue) && !Utility.isEmpty(fieldValue) && fieldValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" checked ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" checked ");
                }
                out.write(" disabled ");
              } else {
                out.write(" disabled ");
              }
              //bill add for EIP-1241 start
              if(Utility.isEmpty(newline)){
                out.println("/>"+tmpFormSelectionFieldOption.getLabel()+brString);
              }else{
                out.println("/>"+tmpFormSelectionFieldOption.getLabel()+brString+newline);
              }
                //bill add for EIP-1241 end

              // is in workflow step process

              if (!isStepElementChange && hasCheckPermission ){
                if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue())){
                  out.println("<input type='hidden' name='"+fieldName+"' value='"+tmpFormSelectionFieldOption.getStartValue()+"' />");
                }
              }
            }
            //END RADIO BOX

            //START CHECK BOX
            else if(FormElementType.ELEMENT_CHECK_BOX.equals(tmpFormElement.getElementType())){

              out.println("<input type='checkbox' name='"+fieldName+"_"+tmpFormSelectionFieldOption.getID()+"' value='"+tmpFormSelectionFieldOption.getStartValue()+"' ");

              String fdefaultValue=(tmpFormElement.getDefaultValue()==null)? "" : tmpFormElement.getDefaultValue();
              if ((!hasCheckPermission || isStepElementChange) && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
                if (!Utility.isEmpty(request.getParameter(fieldName+"_"+tmpFormSelectionFieldOption.getID())) && request.getParameter(fieldName+"_"+tmpFormSelectionFieldOption.getID()).equals(tmpFormSelectionFieldOption.getStartValue()) ){
                  out.write(" checked ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.indexOf(tmpFormSelectionFieldOption.getStartValue())>=0) {
                  out.write(" checked ");
                }
              } else if (!hasCheckPermission || isStepElementRead || isStepElementChange) {
                if (!Utility.isEmpty(request.getParameter(fieldName+"_"+tmpFormSelectionFieldOption.getID())) && request.getParameter(fieldName+"_"+tmpFormSelectionFieldOption.getID()).equals(tmpFormSelectionFieldOption.getStartValue()) ){
                  out.write(" checked ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.indexOf(tmpFormSelectionFieldOption.getStartValue())>=0) {
                  out.write(" checked ");
                }
                out.write(" disabled ");
              } else {
                out.write(" disabled ");
              }
              //bill add for EIP-1241 start
              if(Utility.isEmpty(newline)){
                out.print("/>"+tmpFormSelectionFieldOption.getLabel()+brString);
              }else{
                out.print("/>"+tmpFormSelectionFieldOption.getLabel()+brString+newline);
              }
                //bill add for EIP-1241 end

              // is in workflow step process
              if (hasCheckPermission  &&  !isStepElementChange){
                if (!Utility.isEmpty(elementValue) && elementValue.indexOf(tmpFormSelectionFieldOption.getStartValue())>=0){
                  out.println("<input type='hidden' name='"+fieldName+"' value='"+tmpFormSelectionFieldOption.getStartValue()+"' />");
                }
              }

            }//END CHECK BOX

            //if the form element is a selection box

            //START SELECTION BOX

            else if(FormElementType.ELEMENT_SELECTION_BOX.equals(tmpFormElement.getElementType())){
              if(index==0){
                out.println("<select name='"+fieldName+"' ");

                if(hasCheckPermission && !isStepElementChange || GlobalConstant.NAV_MODE_VIEW.equals(navMode)){
                  out.write(" disabled ");
                }
                out.print(">");
              }

              out.println("<option value='"+tmpFormSelectionFieldOption.getStartValue()+"' ");
              if (!hasCheckPermission && !GlobalConstant.NAV_MODE_VIEW.equals(navMode)) {
                // Use default value just in case specified element value is empty!
                if (Utility.isEmpty(elementValue) && !Utility.isEmpty(fieldValue) && fieldValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" selected ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" selected ");
                }

              } else if (isStepElementRead || isStepElementChange) {
                // Use default value just in case specified element value is empty!
                if (Utility.isEmpty(elementValue) && !Utility.isEmpty(fieldValue) && fieldValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" selected ");
                } else if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue()) ) {
                  out.write(" selected ");
                }
              }

              out.print("/>"+tmpFormSelectionFieldOption.getLabel()+"</option>");

              if (hasCheckPermission && !isStepElementChange ) {
                if (!Utility.isEmpty(elementValue) && elementValue.equals(tmpFormSelectionFieldOption.getStartValue())) {
                  selectedValue = tmpFormSelectionFieldOption.getStartValue();
                }
              }

              if(index==formSelectionFieldOptionList.size()-1){
                out.print("</select>");

                if (!Utility.isEmpty(selectedValue)) {
                  out.println("<input type='hidden' name='"+fieldName+"' value='"+ selectedValue +"' />");
                }

              }
            }//END SELECTION BOX

          }
        }

      }
      if (isAuditColor){
      out.print("</font>");
    }
      out.print("</td>");

    }catch(Exception e){
      log.error(e, e);
    }

  }
  public String getFieldName(FormElement tmpFormElement,Integer pageID,Integer sectionID){
    String FIELD_HEADER = "FB_FIELD_";
    String fieldName = FIELD_HEADER+pageID+"_"+sectionID+"_"+tmpFormElement.getID();
    return fieldName;
  }

  public List getStepElementList(Integer formRecordID,Integer workflowStepID) throws ApplicationException {
    List result = new ArrayList();
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    Integer pageID,sectionID,elementID;
    String formRecordPermission,pagePermission,sectionPermission,elementPermission;

    List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(formRecordID,workflowStepID);
    for (int pp=0; pp<formPageList.size(); pp++){
      FormPage formPage = (FormPage)formPageList.get(pp);
      pageID = formPage.getID();
      formRecordPermission = formPage.getFormRecordPermission();
      if (!Utility.isEmpty(formPage.getPermission())){
        pagePermission = formPage.getPermission();
      }else {
        pagePermission = formRecordPermission;
      }
      List formSectionList = formPage.getFormSectionList();
      for (int i=0; i<formSectionList.size(); i++) {
        FormSection tmpFormSection = (FormSection) formSectionList.get(i);
        if (!Utility.isEmpty(tmpFormSection.getPermission())){
          sectionPermission = tmpFormSection.getPermission();
        }else {
          sectionPermission = pagePermission;
        }
        List formElementList = tmpFormSection.getFormElementList();
        for (int j=0; j<formElementList.size(); j++) {
          FormElement tmpFormElement = (FormElement) formElementList.get(j);
          if (!Utility.isEmpty(tmpFormElement.getPermission())){
            elementPermission = tmpFormElement.getPermission();
          }else {
            elementPermission = sectionPermission;
          }
          if (WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE.equals(elementPermission) || WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(elementPermission) ){
            if (!result.contains(tmpFormElement)){
              result.add(tmpFormElement);
            }
          }
        }
      }
    }
    return result;
  }

  public boolean getRelatedItemPermissionByWorkflowRecordIDFormRecordIDUserRecordIDElementID(Integer workflowRecordID, Integer formRecordID, Integer userRecordID,Integer elementID)throws ApplicationException{
    boolean hasPermission = false;
    Integer workflowStepID = new Integer(0);
    Integer pageID,sectionID;
    String formRecordPermission,pagePermission,sectionPermission,elementPermission;
    //get DAO
    WorkflowStepDAObject workflowStepDAO = new WorkflowStepDAObject(this.sessionCon,this.dbConn);
    FormRecordDAObject formRecordDAO =  new FormRecordDAObject(this.sessionCon,this.dbConn);
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    List stepList = workflowStepDAO.getStepListByWorkflowRecordIDFormRecordIDUserRecordID(workflowRecordID, formRecordID, userRecordID);
    for (int n=0; n<stepList.size(); n++){
      WorkflowStep workflowStep = (WorkflowStep)stepList.get(n);
      workflowStepID = workflowStep.getID();
      List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(formRecordID,workflowStepID);
      for (int pp=0; pp<formPageList.size(); pp++){
        FormPage formPage = (FormPage)formPageList.get(pp);
        pageID = formPage.getID();
        formRecordPermission = formPage.getFormRecordPermission();
        if (!Utility.isEmpty(formPage.getPermission())){
          pagePermission = formPage.getPermission();
        }else {
          pagePermission = formRecordPermission;
        }
        List formSectionList = formPage.getFormSectionList();
        for (int i=0; i<formSectionList.size(); i++) {
          FormSection tmpFormSection = (FormSection) formSectionList.get(i);
          if (!Utility.isEmpty(tmpFormSection.getPermission())){
            sectionPermission = tmpFormSection.getPermission();
          }else {
            sectionPermission = pagePermission;
          }
          List formElementList = tmpFormSection.getFormElementList();
          for (int j=0; j<formElementList.size(); j++) {
            FormElement tmpFormElement = (FormElement) formElementList.get(j);
            if (!Utility.isEmpty(tmpFormElement.getPermission())){
              elementPermission = tmpFormElement.getPermission();
            }else {
              elementPermission = sectionPermission;
            }
            if (WorkflowStep.FORM_PROCESS_PERMISSION_CHANGE.equals(elementPermission) || WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(elementPermission) || WorkflowStep.FORM_PROCESS_PERMISSION_READ.equals(elementPermission)
                || WorkflowStep.FORM_PROCESS_PERMISSION_INHERIT.equals(elementPermission)){
              hasPermission = tmpFormElement.getID().intValue()==elementID.intValue() ?  true : false;
              if (hasPermission){break;}
            }
          }
          if (hasPermission){break;}
        }
        if (hasPermission){break;}
      }
      if (hasPermission){break;}
    }
    return hasPermission;
  }
  // falcon_add_start
  public String isMandatoryBindWFStep(HttpServletRequest request,AbstractActionForm abstractActionForm,Integer pageID,Integer sectionID,FormElement tmpFormElement) throws ApplicationException{
    String isMandatoryBindWFStep=GlobalConstant.FALSE;
    String [] bindWFFormPermission = this.getBindWFFormPermission(request, abstractActionForm, pageID, sectionID,tmpFormElement);
    if(WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(bindWFFormPermission[3])){
      isMandatoryBindWFStep=GlobalConstant.TRUE;
    } else if((WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(bindWFFormPermission[0]) || WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(bindWFFormPermission[1]) || WorkflowStep.FORM_PROCESS_PERMISSION_MANDATORY.equals(bindWFFormPermission[2]))&& WorkflowStep.FORM_PROCESS_PERMISSION_INHERIT.equals(bindWFFormPermission[3])){
      isMandatoryBindWFStep=GlobalConstant.TRUE;
    }
    return isMandatoryBindWFStep;
  }

  public String[] getBindWFFormPermission(HttpServletRequest request,AbstractActionForm abstractActionForm,Integer pageID,Integer sectionID,FormElement tmpFormElement) throws ApplicationException{
    final int formPermissionElementNumber = 4;
    String[] bindWFFormPermission = new String[formPermissionElementNumber];
    if(abstractActionForm instanceof MaintFormSubmissionForm){
     MaintFormSubmissionForm  formSubmissionForm =(MaintFormSubmissionForm)abstractActionForm;
     MtmWfStepFormRecordDAObject wfStepFormRecordDAO=new MtmWfStepFormRecordDAObject(this.sessionCon,this.dbConn);
    if(!Utility.isEmpty(formSubmissionForm.getWorkflowRecordID())){
      String wfRecordID=formSubmissionForm.getWorkflowRecordID();
       WorkflowStepDAObject workflowStepDAO=new WorkflowStepDAObject(this.sessionCon,this.dbConn);
       AbstractBaseObject workflowstep=workflowStepDAO.getSubmitStepByWorkflowRecordID(new Integer(wfRecordID));
       Integer workflowStepID=null;
       if(Utility.isEmpty(request.getParameter("workflowStepID")) || "null".equals(request.getParameter("workflowStepID"))){
         workflowStepID=workflowstep.getID();
       }else{
           workflowStepID=new Integer(request.getParameter("workflowStepID"));
       }
      Integer formRecordID=new Integer(request.getParameter("formRecordID"));
      Integer elementID=null;
      if(!Utility.isEmpty(tmpFormElement.getID())){
        elementID=tmpFormElement.getID();
      }
      bindWFFormPermission[0] = wfStepFormRecordDAO.getFormRecordPermissionByWorkflowStepIDFormRecordID(workflowStepID, formRecordID);
      bindWFFormPermission[1] = wfStepFormRecordDAO.getFormPagePermissionByWorkflowStepIDFormRecordIDFormPageID(workflowStepID, formRecordID, pageID);
      bindWFFormPermission[2] = wfStepFormRecordDAO.getFormSectionPermissionByWorkflowStepIDFormRecordIDFormPageIDFormSectionID(workflowStepID, formRecordID, pageID, sectionID);
      bindWFFormPermission[3] =wfStepFormRecordDAO.getFormElementPermissionByWorkflowStepIDFormRecordIDFormPageIDFormSectionIDFormElementID(workflowStepID, formRecordID, pageID, sectionID, elementID);
      }
    }
   return bindWFFormPermission;
  }
  // falcon_add_end

  /**
   * check if all pages of Form are hide
   * @throws ApplicationException
   */
  public boolean isHideAllPages(Integer formRecordID,Integer workflowStepID) throws ApplicationException{
    FormPageDAObject formPageDAO = new FormPageDAObject(this.sessionCon,this.dbConn);
    List formPageList = formPageDAO.getDetailListByFormRecordIDStepID(formRecordID,workflowStepID);
    if(!Utility.isEmpty(formPageList)){
      for(int i=0;i<formPageList.size();i++){
        FormPage tempFormPage = (FormPage) formPageList.get(i);
        if(!"H".equals(tempFormPage.getPermission())){
          return false;
    }
      }
      return true;//all pages of form are hide
    }else{
      return true;//have no elements so hide it
    }
  }

}